<template>
  <el-col class="cascader-wrapper">
    <el-row :gutter="15" v-if="addressTree.length">
      <el-col :span="9">
        <e-address-cascader class="input-block"
          ref="addressEl"
          placeholder="请选择省市"
          :grade="grade"
          :addressTree="addressTree"
          v-model="addressHead"
          :label.sync="addressLabel"
          @change="handleAddressChange" />
      </el-col>
      <el-col :span="15">
        <el-select class="input-block"
          ref="selectEl"
          multiple
          clearable
          placeholder="请选择"
          v-model="selectedResult"
          @change="handleSelectChange">
          <el-option
            v-for="item in selectsData"
            :key="item.value"
            :label="item.label"
            :value="item">
          </el-option>
        </el-select>
      </el-col>
    </el-row>
  </el-col>
</template>
<script>
  /**
   * 地址级联 + 多选区
   */
  import axios from 'axios'
  import EAddressCascader from '@e-ui/AddressCascader'
  import { ADDRESS_EMPTY_CODE } from '../constant'
  export default {
    components: {
      EAddressCascader
    },
    props: {
      value: {
        type: Array
      },
      type: {
        type: Number,
        default: 1
      },
      props: {
        type: Object
      },
      options: {
        type: Array
      }
    },
    mounted () {
      this.initAddressData()
    },
    data () {
      return {
        grade: 2, // 级别
        selects: [],
        selectsData: [], // 下拉多选数据
        selectedResult: [],
        addressHead: [],
        addressLabel: [],
        addressTree: [] // 地址数据
      }
    },
    methods: {
      initAddressData () {
        // 初始化地址数据
        let result = []
        axios.get('/static/area.json').then(({data}) => {
          this.$areaJson = data
          data.province.forEach(p => {
            let city = []
            let isHasChild = data.city[p.areaId] &&
              this.grade > 1 &&
              ![13257, 13238].includes(p.areaId)
            if (isHasChild) {
              data.city[p.areaId].forEach(c => {
                let area = []
                if (data.area[c.areaId] && this.grade > 2) {
                  data.area[c.areaId].forEach(a => {
                    a.parentId === c.areaId && area.push({
                      value: a.areaId,
                      label: a.title
                    })
                  })
                }
                let cityObject = {
                  value: c.areaId,
                  label: c.title
                }
                if (this.grade > 2 && area.length) {
                  cityObject.children = area
                }
                city.push(cityObject)
              })
            }
            result.push({
              value: p.areaId,
              label: p.title,
              children: isHasChild ? city : null
            })
          })
          this.addressTree = result
          this._initEditValue()
        })
      },
      _initEditValue () {
        // 编辑数据处理
        // 非编辑 不处理
        if (!this.value.length || !this.value[0]) {
          this.addressHead = []
          this.selectedResult = []
          return !1
        }
        // 处理数据
        let addressHeadArr = JSON.parse(this.value[0])
        let addressLabelArr = JSON.parse(this.value[1])
        let isTwoGrade = Boolean(addressHeadArr[0].distinctId === ADDRESS_EMPTY_CODE) // 根据区级ID
        this.addressHead = isTwoGrade ? [addressHeadArr[0].provinceId] : [addressHeadArr[0].provinceId, addressHeadArr[0].cityId]
        this.addressLabel = isTwoGrade ? [addressLabelArr[0].provinceId] : [addressLabelArr[0].provinceId, addressLabelArr[0].cityId]
        // 拼装下拉多选value的对象，要跟handleAddressChange转换一致
        let values = addressHeadArr.map((k, kIndex) => {
          return {
            value: isTwoGrade ? k.cityId : k.distinctId,
            label: isTwoGrade ? addressLabelArr[kIndex].cityId : addressLabelArr[kIndex].distinctId
          }
        })
        this.handleAddressChange(this.addressHead, values)
      },
      handleAddressChange (value, selectedResultCode = []) {
        // 获取地址组件的区 数据
        let areas
        let $areaJson = this.$areaJson
        if (value.length === 1) {
          areas = $areaJson.city[value[0]] || [] // 香港 澳门特殊处理
        } else {
          areas = $areaJson.area[value[1]] || [] // 确保是区 级
        }
        // 拼装下拉多选value的对象，要跟_initEditValue转换一致
        let result = areas.map(k => {
          return {
            value: k.areaId,
            label: k.title
          }
        })
        this.selectsData = result
        // 触发change事件
        this.$nextTick(() => {
          this.selectedResult = selectedResultCode
        })
      },
      handleSelectChange (value) {
        let values = []
        let valueTexts = []
        let isTwoGrade = Boolean(this.addressHead.length === 1) // 是否只有两级
        let addressHeadObj = {
          provinceId: this.addressHead[0],
          cityId: this.addressHead[1]
        }
        let addressLabelObj = {
          provinceId: this.addressLabel[0],
          cityId: this.addressLabel[1]
        }
        value.forEach(item => {
          // code
          values.push(Object.assign({}, addressHeadObj, {
            cityId: isTwoGrade ? item.value : addressHeadObj.cityId,
            distinctId: isTwoGrade ? ADDRESS_EMPTY_CODE : item.value // 作为港澳 只有二级的特殊处理
          }))
          // name
          valueTexts.push(Object.assign({}, addressLabelObj, {
            cityId: isTwoGrade ? item.label : addressLabelObj.cityId,
            distinctId: isTwoGrade ? '' : item.label
          }))
        })
        // 触发更新
        if (values.length) {
          this.$emit('change', {
            value: [JSON.stringify(values)],
            valueTexts: [JSON.stringify(valueTexts)]
          })
        } else {
          this.$emit('change', {
            addressHead: addressHeadObj
          })
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .cascader-wrapper{
    width: 578px;
  }
</style>
